package com.example.administrator.liveapp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.ActionActivity;
import com.example.administrator.liveapp.activity.LiveDetailsPage;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.base.BaseRVAdapter;
import com.example.administrator.liveapp.base.BaseViewHolder;
import com.example.administrator.liveapp.bean.ActivityColumnBean;
import com.example.administrator.liveapp.bean.ActivityListBean;
import com.example.administrator.liveapp.bean.LiveListBean;
import com.example.administrator.liveapp.bean.VideoColumnBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.LogU;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播列表Fragment
 */

public class LiveManFragment extends BaseFragment implements View.OnClickListener {

    private RecyclerView type, content;
    private View view;
    private TextView tv_title;
    private ImageView top_img;
    private LinearLayout top_img_line;
    private VideoColumnBean bean;
    private LiveListBean bean2;
    private TextView item_action_null;
    private RelativeLayout activity_relat,top;
    private View loadView;//loding页面（加载页）

    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;

    public View initView() {
        view = View.inflate(mContext, R.layout.activity_action1, null);
        loadView = view.findViewById(R.id.loadView);
        top_img_line = (LinearLayout) view.findViewById(R.id.top_img_line);
        top_img = (ImageView) view.findViewById(R.id.top_img);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        type = (RecyclerView) view.findViewById(R.id.type);
        content = (RecyclerView) view.findViewById(R.id.content);
        item_action_null = (TextView) view.findViewById(R.id.item_action_null);
        activity_relat = (RelativeLayout) view.findViewById(R.id.activity_relat);
        top = (RelativeLayout) view.findViewById(R.id.top);
        top.setVisibility(View.GONE);
        top_img.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getActivity().getWindowManager().getDefaultDisplay().getWidth() / 16 * 9));
        top_img.setOnClickListener(this);
        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout)view.findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        initData();
        return view;
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
    }

    public List<Boolean> isClicks;//控件是否被点击,默认为false，如果被点击，改变值，控件根据值改变自身颜色

//    @Override
//    public void onPause() {
//        super.onPause();
//        initData();
//    }

    public void initData() {
        String url = AppUrl.URL+ AppUrl.VideoColumn;
        XUtils.Get(url,null,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, VideoColumnBean.class);
                String Url = bean.getVideoImg().getVideoimgurl();
                String ImageUrl = "";
                if (Url != null && !Url.equals("")) {
                    ImageUrl = Url.substring(1, Url.indexOf("|"));
                }
                Glide.with(mContext)
                        .load(AppUrl.URL+ImageUrl)
                        .into(top_img);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
                    @Override
                    public void onLoadmore(RefreshLayout refreshlayout) {
                        //底部加载
                    }

                    @Override
                    public void onRefresh(final RefreshLayout refreshlayout) {
                        //下拉刷新
                        refreshlayout.getLayout().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                initData();
                                refreshlayout.finishRefresh();
                            }
                        }, 2000);
                    }
                });
                setData();
                loadView.setVisibility(View.GONE);
                isClicks = new ArrayList<>();
                for(int i = 0;i<bean.getColumn().size();i++){
                    if(i==0){
                        isClicks.add(true);
                    }
                    isClicks.add(false);
                }
                String url = AppUrl.URL+ AppUrl.VideoList;
                Map<String,String> map = new HashMap();
                map.put("column","全部");
                XUtils.Get(url,map,new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Gson gson = new Gson();
                        bean2 = gson.fromJson(result, LiveListBean.class);
                        initData2();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        Toast.makeText(mContext, ex.getMessage()+"", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }
                });
            }
        });


    }

    public void setData() {
        tv_title.setText("直播");
        FullyLinearLayoutManager fullyLinearLayoutManager = new FullyLinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        fullyLinearLayoutManager.setScrollEnabled(false);
        type.setLayoutManager(fullyLinearLayoutManager);
        type.setAdapter(new BaseRVAdapter(mContext, bean.getColumn()) {

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_action_type;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                final TextView text = holder.getTextView(R.id.text);
                text.setText(bean.getColumn().get(position).getColumnname());
                if(isClicks.get(position)){
                    text.setBackgroundResource(R.drawable.b9_circle_main);
                    text.setTextColor(Color.parseColor("#FFFFFF"));
                }else{
                    text.setBackgroundResource(R.drawable.b9_circle_white);
                    text.setTextColor(Color.parseColor("#7FC48D"));
                }

                addItemClickListener(new OnItemClickListener() {
                    @Override
                    public void itemSelect(final int positions) {
                        if (positions == 0) {
                            String url = AppUrl.URL+ AppUrl.VideoList;
                            Map<String,String> map = new HashMap();
                            map.put("column","全部");
                            XUtils.Get(url,map,new MyCallBack<String>(){
                                @Override
                                public void onSuccess(String result) {
                                    super.onSuccess(result);
                                    String video="";
                                    Gson gson = new Gson();
                                    try {
                                        JSONObject json = new JSONObject(result);
                                        video = json.optString("result");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    bean2.getVideo().clear();
                                    bean2 = gson.fromJson(result, LiveListBean.class);
                                    if(video.equals("false")){
                                        item_action_null.setVisibility(View.VISIBLE);
                                        content.setVisibility(View.GONE);
                                    }else{
                                        item_action_null.setVisibility(View.GONE);
                                        content.setVisibility(View.VISIBLE);
                                        initData2();
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    Toast.makeText(mContext, ex.getMessage()+"", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onFinished() {
                                    super.onFinished();
                                    for(int i = 0; i <isClicks.size();i++){
                                        isClicks.set(i,false);
                                    }
                                    isClicks.set(positions,true);
                                    notifyDataSetChanged();
                                }
                            });
                            return;
                        }
                        String url = AppUrl.URL+ AppUrl.VideoList;
                        Map<String,String> map = new HashMap();
                        map.put("column",bean.getColumn().get(positions).getColumnname());
                        XUtils.Get(url,map,new MyCallBack<String>(){
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                String video="";
                                LogU.e("----",result);
                                Gson gson = new Gson();
                                try {
                                    JSONObject json = new JSONObject(result);
                                    video = json.optString("result");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                bean2.getVideo().clear();
                                bean2 = gson.fromJson(result, LiveListBean.class);
                                if(video.equals("false")){
                                    item_action_null.setVisibility(View.VISIBLE);
                                    content.setVisibility(View.GONE);
                                }else{
                                    item_action_null.setVisibility(View.GONE);
                                    content.setVisibility(View.VISIBLE);
                                    initData2();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(mContext, ex.getMessage()+"错误", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                for(int i = 0; i <isClicks.size();i++){
                                    isClicks.set(i,false);
                                }
                                isClicks.set(positions,true);
                                notifyDataSetChanged();
                            }
                        });
                    }
                });
            }

        });

    }

    private void initData2() {
        FullyLinearLayoutManager fullyLinearLayoutManager1 = new FullyLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        fullyLinearLayoutManager1.setScrollEnabled(false);
        content.setLayoutManager(fullyLinearLayoutManager1);
        content.setAdapter(new BaseRVAdapter(mContext, bean2.getVideo()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_video;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                if(bean2.getVideo().get(position).getVideoImgUrl()!=null){
                    Glide.with(mContext)
                            .load(AppUrl.URL+bean2.getVideo().get(position).getVideoImgUrl().substring(1,bean2.getVideo().get(position).getVideoImgUrl().indexOf("|")))
                            .into(holder.getImageView(R.id.activity_image));
                }
                holder.getTextView(R.id.activity_title).setText(bean2.getVideo().get(position).getVideoTitle());
                holder.getTextView(R.id.activity_name).setText(bean2.getVideo().get(position).getVideoAuthor());
                holder.getTextView(R.id.like_text).setText(bean2.getVideo().get(position).getLikeCount().toString());
                holder.getTextView(R.id.view_text).setText(bean2.getVideo().get(position).getVideoViewCount());
                holder.getTextView(R.id.activity_price).setText(bean2.getVideo().get(position).getVideoPrice());
                if(!bean2.getVideo().get(position).getNowPrice().equals("0.00")&&!bean2.getVideo().get(position).getNowPrice().equals("0")){
                    holder.getTextView(R.id.now_price).setText("¥ "+bean2.getVideo().get(position).getNowPrice());
                    holder.getTextView(R.id.now_price).setTextColor(Color.parseColor("#999999"));
                }else{
                    holder.getTextView(R.id.now_price).setText("免费");
                    holder.getTextView(R.id.now_price).setTextColor(Color.parseColor("#999999"));
                }
                if(bean2.getVideo().get(position).getVideoColumn().equals("")){
                    holder.getTextView(R.id.video_column).setVisibility(View.GONE);
                }else{
                    holder.getTextView(R.id.video_column).setVisibility(View.VISIBLE);
                    holder.getTextView(R.id.video_column).setText(bean2.getVideo().get(position).getVideoColumn());
                }

                addItemClickListener(new OnItemClickListener() {
                    @Override
                    public void itemSelect(int position) {
                        Intent intent = new Intent(mContext, LiveDetailsPage.class);
                        intent.putExtra("videoId",bean2.getVideo().get(position).getVideoId());
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                    }
                });
            }
        });
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_img:
                Intent intent = new Intent(mContext,LiveDetailsPage.class);
                intent.putExtra("videoId",bean.getVideoImg().getVideoid());
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                break;
        }
    }
}
